
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.sku_serializers import *
from meiduo_admin.paginators import MyPage

class SKUViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            # 如果查询字符串有keyword则过滤查询返回
            return self.queryset.filter(name__contains=keyword)
        # 否则返回所有数据查询集
        return self.queryset.all()


class SKUCategoryView(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent_id__gt=37)
    serializer_class = SKUCategoryModelSerializer


class SPUSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSimpleModelSerializer


class SpecListView(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SpecModelSerializer

    def get_queryset(self):
        # 过滤出路径中spu_id关联的所有的规格查询集
        # 问题：如何在非视图函数中，获取路径参数？
        # 答：self.kwargs --> 是一个字典封装了路径关键字参数
        spu_id = self.kwargs.get('pk')
        return self.queryset.filter(
            spu_id=spu_id # 路径中的参数spu_id
        )
